import React from 'react'
import { Button, Form, Input, DatePicker, Row, Col, TreeSelect, Table, message, Modal, Tag } from 'antd';
import {
  SettingOutlined,
  EyeOutlined,
} from '@ant-design/icons'
import { getRoleApi, delRoleApi } from '../../../apis/system';
import RoleDrawer from './RoleDrawer'
const { RangePicker } = DatePicker
export default function User() {

  const [data, setData] = React.useState([])
  const [total, setTotal] = React.useState(0)
  const [current, setCurrent] = React.useState(1)
  const [selectedRowKeys, setSelectedRowKeys] = React.useState([]);
  const [curRoleInfo, setCurRoleInfo] = React.useState(null)
  const [isShowDrawer, setIsShowDrawer] = React.useState(false)
  const [sortedInfo, setSortedInfo] = React.useState({})
  const [tableParams, setTableParams] = React.useState({})
  const [searchParams, setSearchParams] = React.useState({})
  const [showItem, setShowItem] = React.useState(false)
  const checkedItemsRef = React.useRef([])
  const searchRef = React.useRef(null)
  React.useEffect(() => {
    getRoleData()
  }, [])

  // 获取数据
  function getRoleData(params) {
    // console.log(111);
    getRoleApi(params).then(res => {
      console.log(res.rows);
      setData(res.rows)
      setTotal(res.total)
    })
  }

  // 选中
  const onSelectChange = (newSelectedRowKeys, selectedRows) => {
    // console.log(selectedRows);
    // console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
    checkedItemsRef.current = selectedRows
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  // 删除
  function del() {
    // console.log(checkedItemsRef.current);
    if (!checkedItemsRef.current.length) {
      message.info('请选择要删除的角色')
    } else {
      const ids = checkedItemsRef.current.map(item => item.roleId).join(',')
      const names = checkedItemsRef.current.map(item => item.roleName).join(',')
      Modal.confirm({
        title: '提示',
        content: <div>
          确定删除以下角色吗?<br />
          {names}
        </div>,
        onOk() {
          delRoleApi(ids).then(() => {
            getRoleData()
            checkedItemsRef.current = []
            message.success('删除成功')
            setCurrent(1)
          })
        }
      })
    }
  }

  // 新增
  function add() {
    setIsShowDrawer(true)
  }

  // 编辑角色
  function editRole(item,flag) {
    setIsShowDrawer(true)
    // setCurUserInfo(item)
    // console.log(item);
    setCurRoleInfo(item)
    setShowItem(flag)
  }

  // 关闭抽屉
  function closeDrawer(flag) {
    setIsShowDrawer(false)
    setCurRoleInfo(null)
    setShowItem(false)
    if (flag == 'update') {
      // console.log(1);
      getRoleData()
      setCurrent(1)
    }
  }

  // 表格换页，排序，筛选
  const handleChange = (pagination, filters, sorter) => {
    // console.log('Various parameters', pagination, filters, sorter);

    console.log('sorter', sorter);
    console.log(pagination);

    setSortedInfo(sorter);
    setCurrent(pagination.current)
    // console.log(sortedInfo);
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    }
    if (sorter.field && sorter.order) {
      params.sortOrder = sorter.order
      params.sortField = sorter.field
    }
    setTableParams(params)
    getRoleData({ ...searchParams, ...params })
  };

  // 重置
  function reset() {
    setSortedInfo({})
    setTableParams({})
    setSearchParams({})
    setCurrent(1)
    searchRef.current.resetFields()
    getRoleData()
  }

  // 查询
  const onFinish = (values) => {
    console.log('Success:', values);
    const params = {
      roleName: values.roleName,
    }
    if (values.time) {
      params.createTimeFrom = values.time[0].format('YYYY-MM-DD')
      params.createTimeTo = values.time[1].format('YYYY-MM-DD')
    }
    setSearchParams(params)
    getRoleData({ ...tableParams, ...params })
  };

  function download() {
    downloadInfoApi('role')
  }

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };


  const columns = [
    {
      title: '角色名',
      dataIndex: 'roleName',
      // key: 'username'
    },
    {
      title: '描述',
      dataIndex: 'remark',
      // key:'ssex',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      sortOrder: sortedInfo.field == 'createTime' ? sortedInfo.order : null,
    },
    {
      title: '修改时间',
      dataIndex: 'modifyTime',
      sorter: true,
      sortOrder: sortedInfo.field == 'modifyTime' ? sortedInfo.order : null,
    },
    {
      title: '操作',
      render: (item) => (
        <div>
          <SettingOutlined style={{ color: '#1890ff', marginRight: '10px' }} onClick={() => editRole(item,false)} />
          <EyeOutlined style={{ color: 'rgb(66, 185, 131)' }} onClick={()=>editRole(item,true)}/>
        </div>
      )
    }
  ];

  return (
    <div>
      <Form
        name="basic"
        labelCol={{
          span: 4,
        }}
        wrapperCol={{
          span: 18,
        }}
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        ref={searchRef}
      >
        <Row>
          <Col span={10}>
            <Form.Item
              label="角色名"
              name="roleName"
            >
              <Input />
            </Form.Item>
          </Col>
          <Col span={10}>
            <Form.Item label="创建时间" name='time'>
              <RangePicker />
            </Form.Item>
          </Col>
          <Col span={4}>
            <Form.Item
              wrapperCol={{
                // offset: 16,
                // span: 16,
              }}
              labelAlign={'right'}
            >

              <Button type="primary" htmlType="submit" style={{ marginRight: '20px' }}>
                查询
              </Button>
              <Button onClick={reset}>
                重置
              </Button>

            </Form.Item>
          </Col>
        </Row>
      </Form>
      <Button type='primary' ghost={true} style={{ marginRight: '20px', marginBottom: '20px' }} onClick={add}>新增</Button>
      <Button onClick={del} style={{ marginRight: '20px' }}>删除</Button>
      <Button onClick={download}>
        导出Excel
      </Button>
      <Table
        columns={columns}
        dataSource={data}
        rowKey='roleId'
        pagination={{ total, current, pageSizeOptions: ['10', '20', '30'], showSizeChanger: true, showQuickJumper: true }}
        rowSelection={rowSelection}
        onChange={handleChange}
      />
      <RoleDrawer curRoleInfo={curRoleInfo} visible={isShowDrawer} closeDrawer={closeDrawer} lookOrEdit={showItem}></RoleDrawer>

    </div>
  )
}
